package jiang.app.service;

import java.util.HashMap;

import javax.servlet.http.HttpSession;

import jiang.app.entity.User;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class HomeService {
	@Autowired
	UserService userService;
	
	public HashMap<String, Object> login(User u, boolean rememberMe){
		User user = userService.findUserByUsernameAndPassword(u);
		HashMap<String, Object> m = new HashMap<String, Object>();
		if(user != null){
			m.put("success", true);
			m.put("user", user);
			shiroLogin(u, rememberMe);
		}
		else{
			m.put("success", false);
		}
		return m;
	}
	
	public void shiroLogin(User u, boolean rememberMe){
		UsernamePasswordToken token = new UsernamePasswordToken();
		token.setUsername(u.getUsername());
		token.setPassword(u.getPassword().toCharArray());
		token.setRememberMe(rememberMe);
		SecurityUtils.getSubject().login(token);
	}
	
	public void shiroLogout(){
		SecurityUtils.getSubject().logout();
	}
}
